<template>
  <view class="admin-login-page">
    <view class="login-container">
      <view class="logo-area">
        <view class="logo">🖼️</view>
        <text class="app-name">壁纸库管理系统</text>
        <text class="slogan">管理员登录</text>
      </view>
      
      <view class="login-form">
        <view class="form-item">
          <text class="label">用户名</text>
          <input 
            v-model="loginForm.username" 
            type="text" 
            placeholder="请输入用户名"
            class="form-input"
            @keyup.enter="handleLogin"
          />
        </view>
        
        <view class="form-item">
          <text class="label">密码</text>
          <view class="password-input">
            <input 
              :password="!showPassword" 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              class="form-input"
              @keyup.enter="handleLogin"
            />
            <view class="password-toggle" @click="togglePasswordVisibility">
              <text style="font-size: 16px;">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
            </view>
          </view>
        </view>
        
        <button 
          class="login-btn" 
          type="primary" 
          :disabled="!canLogin || isLoading"
          @click="handleLogin"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </view>
      
      <view class="tips">
        <text class="tip-text">默认账号: admin123</text>
        <text class="tip-text">默认密码: admin123</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import {onLoad} from "@dcloudio/uni-app"

// 状态管理
const loginForm = reactive({
  username: '',
  password: ''
});
const showPassword = ref(false);
const isLoading = ref(false);

// 生命周期
onLoad(() => {
  // 检查是否已登录
  const adminToken = uni.getStorageSync('admin_token');
  if (adminToken) {
    uni.redirectTo({ url: '/pages/admin/index' });
  }
});

// 计算属性
const canLogin = computed(() => {
  return loginForm.username.trim().length > 0 && 
         loginForm.password.trim().length > 0;
});

// 切换密码可见性
const togglePasswordVisibility = () => {
	console.log(showPassword.value);
  showPassword.value = !showPassword.value;
};

// 处理登录
const handleLogin = async () => {
	console.log('数据',loginForm);
  if (!canLogin.value || isLoading.value) return;
  
  try {
    isLoading.value = true;
    uni.showLoading({ title: '登录中' });
    
    // 尝试调用云函数
    try {
      const result = await uniCloud.callFunction({
        name: 'adminlogin',
        data: {
          username: loginForm.username.trim(),
          password: loginForm.password.trim()
        }
      });
      
      uni.hideLoading();
      
      if (result && result.result && result.result.code === 0) {
        // 保存登录状态
        uni.setStorageSync('admin_token', result.result.token || 'mock_admin_token');
        uni.setStorageSync('admin_info', result.result.adminInfo || { 
          username: loginForm.username.trim()
        });
        
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500,
          complete: () => {
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/admin/index' });
            }, 1500);
          }
        });
      } else {
        uni.showToast({ 
          title: result.result?.message || '账号或密码错误', 
          icon: 'none' 
        });
      }
    } catch (cloudError) {
      console.log('管理员登录云函数调用失败，使用模拟登录:', cloudError);
      uni.hideLoading();
      
      // 模拟登录成功（用于开发测试）
      if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
        const mockToken = 'mock_admin_token_' + Date.now();
        const mockUserInfo = { 
          username: 'admin', 
          role: 'admin',
          loginTime: new Date().toISOString()
        };
        
        uni.setStorageSync('admin_token', mockToken);
        uni.setStorageSync('admin_info', mockUserInfo);
        
        uni.showToast({
          title: '模拟登录成功',
          icon: 'success',
          duration: 1500,
          complete: () => {
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/admin/index' });
            }, 1500);
          }
        });
      } else {
        uni.showToast({ 
          title: '账号或密码错误', 
          icon: 'none' 
        });
        // 提示默认账号密码
        setTimeout(() => {
          uni.showModal({
            title: '测试账号',
            content: '默认账号: admin\n默认密码: admin123',
            showCancel: false
          });
        }, 1500);
      }
    }
  } catch (error) {
    console.error('登录失败:', error);
    isLoading.value = false;
    uni.hideLoading();
    uni.showToast({ 
      title: '登录失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped lang="less">
.admin-login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  
  .login-container {
    width: 100%;
    max-width: 400px;
    background-color: #fff;
    border-radius: 20px;
    padding: 32px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
    
    .logo-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 32px;
      
      .logo {
        font-size: 64px;
        margin-bottom: 16px;
      }
      
      .app-name {
        font-size: 20px;
        font-weight: 700;
        color: #333;
        margin-bottom: 8px;
      }
      
      .slogan {
        font-size: 14px;
        color: #666;
      }
    }
    
    .login-form {
      .form-item {
        margin-bottom: 24px;
        
        .label {
          display: block;
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
          font-weight: 500;
        }
        
        .form-input {
          width: 100%;
          height: 48px;
          padding: 0 16px;
          background-color: #f8f8f8;
          border: 1px solid #e0e0e0;
          border-radius: 12px;
          font-size: 16px;
          box-sizing: border-box;
        }
        
        .password-input {
          position: relative;
          
          .password-toggle {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
          }
        }
      }
      
      .login-btn {
        width: 100%;
        height: 48px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 12px;
      }
    }
    
    .tips {
      margin-top: 24px;
      text-align: center;
      
      .tip-text {
        display: block;
        font-size: 12px;
        color: #999;
        margin-bottom: 4px;
      }
    }
  }
}
</style>